package com.authine.cloudpivot.ext.controller.fileInfo.com;

import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 *  公司级档案部门授权信息
 **/
@RestController
@RequestMapping("/public/CompanyDeptAuth")
@Slf4j
public class ComDepartmentAuthInfoController extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     *  公司级档案部门授权信息  审批流完成后 数据写到基础表-公司级档案中间组织授权信息(公司级档案部门授权信息)
     */
    @Async
    @RequestMapping("empower")
    public void empower(@RequestParam String   bizId){
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.ComDepartmentAuthInfo, bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");
        log.error("基础表-公司档案   list.bizId", bizId);

//        Object pushAllResult = bizObject.get("pushAllResult");


        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("comDepartmentAuthInfoSheet1");
        log.error("基础表-公司档案   list.size", list.size());
        log.error("基础表-公司档案   list.get(0)", list.get(0).toString());

        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        //获取审批人
        String approvalType = (String) list.get(0).get("approvalType");
//        String approval = getFileBaseInfoWorkFlowApproval(bizObject, approvalType);
        String approval = "";


        for (Map<String, Object> map : list) {
            String fileCode = (String) map.get("fileCode");

            try {

                //调用存储过程
                callProcess(map, approval);

            } catch (Exception e) {
                log.info("基础表-公司档案  添加失败 fileCode={}", fileCode);
                log.info(e.getMessage(), e);
            }

        }
    }

    /**
     *  调用存储过程
     ----公司级档案授权信息			----2023.03.22
     exec   SyncComArchAuth
     @companyCode      nvarchar(100),			----公司代码
     @number		  nvarchar(100),			----档案代码
     @deptcode  	  nvarchar(100),			----授权需求部门代码
     @RIGHT		  nvarchar(10),				----授权   1  ☆  2  △  3 √
     @AuthPosCode	  nvarchar(100),			----授权需求部门责任岗代码
     @Auditor	  nvarchar(50)				----审批人  02.0100 张三
     */
    private void callProcess(Map<String, Object> map, String approval){

        if (ObjectUtils.isEmpty(map)) {
            return;
        }

        log.info("入参map={}", map);

        //调用存储过程
        String companyNumber = MapUtils.getString(map, "companyCode", "");//公司代码
        String fileCode = MapUtils.getString(map, "fileCode", "");//档案代码
        String authDeptNumber = MapUtils.getString(map, "authDeptNumber", "");//授权需求部门代码
        String purview = MapUtils.getString(map, "purview", "");//权限      1  五角    2  三角    3 √
        String purviewValue = "";
        purview = purview == null ? "" : purview;
        switch (purview) {
            case "★":
                purviewValue = "1";
                break;
            case "▲":
                purviewValue = "2";
                break;
            case "√":
                purviewValue = "3";
                break;
        }


        String authReqDeptResPosNumber = MapUtils.getString(map, "authReqDeptResPosNumber", "");//授权需求部门责任岗代码



        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncComArchAuth '%s','%s','%s','%s','%s','%s'",
                companyNumber, fileCode, authDeptNumber, purviewValue, authReqDeptResPosNumber,
                approval);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }

    /**
     *  查询审批人,返回  员工号+姓名
     * @param bizObject
     * @param approvalType
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject, String approvalType) {
        String mainDeptCode = (String) bizObject.get("mainDeptCode");
        String activityCode ="";
        if ("01".equals(approvalType)){
            String manageDeptCode = (String) bizObject.get("manageDeptCode");
            if (mainDeptCode.equals(manageDeptCode)){
                activityCode="Activity11";
            }else{
                activityCode="Activity13";

            }
        }else if("03".equals(approvalType)) {
            String frameDeptCode = (String) bizObject.get("frameDeptCode");
            if (mainDeptCode.equals(frameDeptCode)){
                activityCode="Activity16";
            }else{
                activityCode="Activity20";
            }
        }


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = activityCode;
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(user.getName()).toString();
    }



    /**
     * 判断是否已存在
     * @param field
     * @param value
     * @param schemaCode
     * @return
     */
    private String existsBizObject(String field,String value,String schemaCode){

        String tableName = getBizObjectFacade().getTableName(schemaCode);

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where ").append(field).append("='").append(value).append("'");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     *  转换成  基础表-总公司档案 的数据
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String,Object> fileInfoBaseMap(Map<String,Object> map,String auditDate,String auditer){
        Map<String, Object> data = new HashMap<>();

        //审批类型
        data.put("approvalType",map.get("approvalType"));
        //档案类型号
        data.put("archTypeNumber",map.get("archTypeNumber"));
        //审批时间
        data.put("auditDate",map.get("auditDate"));
        //审批人
        data.put("auditer",map.get("auditer"));
        //授权需求部门代码
        data.put("authDeptId",map.get("authDeptId"));
        //授权需求部门
        data.put("AuthDeptName",map.get("AuthDeptName"));
        //授权需求部门代码
        data.put("authDeptNumber",map.get("authDeptNumber"));
        //授权需求部门责任岗代码
        data.put("authReqDeptResPosId",map.get("authReqDeptResPosId"));
        //授权需求部门责任岗
        data.put("authReqDeptResPosName",map.get("authReqDeptResPosName"));
        //授权需求部门责任岗代码隐藏
        data.put("authReqDeptResPosNumber",map.get("authReqDeptResPosNumber"));
        //基础代码
        data.put("baseCode",map.get("baseCode"));
        //基础代码关联
        data.put("basicCode",map.get("basicCode"));
        //公司代码
        data.put("companyCode",map.get("companyCode"));
        //说明
        data.put("des",map.get("des"));
        //电子版
        data.put("elec",map.get("elec"));
        //档案代码
        data.put("fileCode",map.get("fileCode"));
        //档案名称
        data.put("fileName",map.get("fileName"));
        //档案代码关联
        data.put("fileNumber",map.get("fileNumber"));
        //工作说明
        data.put("jobDesc",map.get("jobDesc"));
        //主责部门
        data.put("mainDepartmentName",map.get("mainDepartmentName"));
        //主责部门代码
        data.put("mainDepartmentNumber",map.get("mainDepartmentNumber"));
        //主责岗代码
        data.put("mainPositionCode",map.get("mainPositionCode"));
        //主责岗代码关联
        data.put("mainPositionId",map.get("mainPositionId"));
        //主责岗
        data.put("mainPostionName",map.get("mainPostionName"));
        //主责人
        data.put("mainUser",map.get("mainUser"));
        //管理部门代码
        data.put("manaDeptId",map.get("manaDeptId"));
        //管理部门
        data.put("manaDeptName",map.get("manaDeptName"));
        //管理职能
        data.put("manageFun",map.get("manageFun"));
        //名称
        data.put("name01",map.get("name01"));
        //岗A
        data.put("positionAName",map.get("positionAName"));
        //岗B关联
        data.put("positionB",map.get("positionB"));
        //岗B代码
        data.put("positionBCode",map.get("positionBCode"));
        //岗A代码
        data.put("postionACode",map.get("postionACode"));
        //岗B
        data.put("postionBname",map.get("postionBname"));
        //授权
        data.put("purview",map.get("purview"));
        //对应记录
        data.put("record",map.get("record"));
        //对应说明
        data.put("refDes",map.get("refDes"));
        //公司关联
        data.put("relevCompany",map.get("relevCompany"));
        //关联管理部门
        data.put("relevManageDept",map.get("relevManageDept"));
        //岗A关联
        data.put("relevPositionA",map.get("relevPositionA"));
        //关联类型职能
        data.put("relevTypeFun",map.get("relevTypeFun"));
        //备注
        data.put("remarks",map.get("remarks"));
        //序号
        data.put("serialNo",map.get("serialNo"));
        //档案类型缩略语
        data.put("archTypeAcronym",map.get("archTypeAcronym"));
        //上级权限
        data.put("superAuth",map.get("superAuth"));
        //上级组织
        data.put("superOrg",map.get("superOrg"));
        //上级组织责任岗
        data.put("supOrgResPosName",map.get("supOrgResPosName"));
        //上级组织责任岗代码
        data.put("supOrgResPosNumber",map.get("supOrgResPosNumber"));
        //档案类型
        data.put("typeName",map.get("typeName"));
        //序号
        data.put("xh",map.get("xh"));
        //职能
        data.put("zn",map.get("zn"));
        //职能
        data.put("znCode",map.get("znCode"));
        //职能名称
        data.put("znName",map.get("znName"));

        //审批时间
        data.put("auditDate",auditDate);
        //审批人
        data.put("auditer",auditer);
        return data;
    }
}
